package com.tqyan.service.service.impl;

import com.tqyan.model.dto.UserDTO;
import com.tqyan.model.exp.DefaultException;
import com.tqyan.service.service.AccountService;
import com.tqyan.service.service.SoundService;
import com.tqyan.service.service.UserService;
import com.tqyan.service.transfer.xunfei.SoundDictationWebSocketListener;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 语音服务
 * <p> <功能详细描述> </p>
 *
 * @author 陈晨
 * @version 1.0
 * @date 2023/4/15
 */
@Service
@Slf4j
public class SoundServiceImpl implements SoundService {
    public static final String APP_ID = "eafeff66";
    public static final String API_SECRET = "YTYzNGE3YzEwYzVjYjYxMjk3MDgwNjg1";
    public static final String API_KEY = "61a925fbf5e546076906b293c97ac5a9";

    private static final long TIME_OUT = 5000;

    @Autowired
    private UserService userService;
    @Autowired
    private AccountService accountService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String soundDictation(String openId, FileInputStream input) {
        // 费用扣除
        UserDTO user = userService.getUserInfo(openId);
//        // 是否欠费
//        if (accountService.isArrears(user.getId(), 1)) {
//            throw new DefaultException("501", "余额不足");
//        }
//        boolean consumptionResult = accountService.consumption(user.getId(), 1, "语音识别");
//        log.info("[科大讯飞] userId={}, 语音识别费用扣除, 添加账单: {}", user.getId(), consumptionResult);
        // 语音识别
        long beginTime = System.currentTimeMillis();
        AtomicReference<String> content = new AtomicReference<>();
        try {
            SoundDictationWebSocketListener xunfei = new SoundDictationWebSocketListener(
                SoundServiceImpl.APP_ID, SoundServiceImpl.API_SECRET, SoundServiceImpl.API_KEY
                , input, result -> {
                    if (!result.isResult()) {
                        throw new DefaultException(result.getData());
                    }
                    content.set(result.getData().trim());
                }
            );
            String authUrl = xunfei.getAuthUrl(SoundDictationWebSocketListener.HOST_URL);
            String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
            Request request = new Request.Builder().url(url).build();
            OkHttpClient client = new OkHttpClient.Builder().build();
            client.newWebSocket(request, xunfei);
        } catch (Exception e) {
            log.error("[科大讯飞] 语音识别异常: {}", e.getMessage(), e);
            throw new DefaultException("对不起, 小燕子没听太清楚");
        }
        // 等待响应
        while (StringUtils.isBlank(content.get()) && System.currentTimeMillis() - beginTime < TIME_OUT) {
            try {
                Thread.sleep(300L);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        if (StringUtils.isBlank(content.get())) {
            throw new DefaultException("小燕子太累了, 让它休息一会吧");
        }
        return content.get();
    }

}


